<?php
// Login page for Larch, the Language Archive software.

require_once('config.php');
require_once('functions.php');
require_once('db.php');

// Check for cookie availability.
if (!array_key_exists($larch_pfx . 'cookie', $_COOKIE)) {
	// This sets a cookie and if successful sends the user back to this
	// page. If unsuccessful it sends the user to cookiefail.php instead.
	header("Location: cookietest.php");
}

session_start();

// This function validates the username and password against the database.
// Returns usr_id on success, otherwise a string containing the error message.
function check_user($form, $db) {
	$username = $form['username'];
	$password = $form['password'];

	// Some basic error checking.
	if (trim($username) == "") {
		return errmsg("Username required.");
	} elseif (trim($password) == "") {
		return errmsg("Password required.");
	}

	// Input security.
	if (strpos($username, ";")) {
		return errmsg("Invalid character in username.");
	}

	// Look up user in the database.
	// FIXME: Client side (JS) encryption? Or just get SSL working.
	$query_values = array('usr_username' => $username,
			      'usr_password' => $password);
	$query = "SELECT usr_id FROM users ";
	$query .= sprintf("WHERE usr_username = '%s' "
		          . "AND usr_password = password('%s')",
			  $username, $password);
	$rs = mysql_query($query, $db) or die(mysql_errno_error());

	// Valid user?
	if (mysql_num_rows($rs) == 0) {
		// NOTE: We don't say whether it was the username or password
		// that was wrong. This is intentional.
		return errmsg("Invalid username or password");
	} elseif (mysql_num_rows($rs) > 1) {
		// Can't happen because usr_username is a unique key.
		return errmsg("Can’t happen: multiple users returned!");
	}

	// Yes, return user id.
	$row = mysql_fetch_assoc($rs);
	return (int) $row['usr_id'];
}

//
// Do something.
//

require($smarty_source);
$smarty = new Smarty();
$smarty->template_dir = $smarty_tpl;
$smarty->compile_dir = $smarty_compile_dir;
$smarty->config_dir = $smarty_config_dir;
$smarty->cache_dir = $smarty_cache_dir;
$smarty->debugging = $smarty_dbg;

$smarty->assign('larch_name', $larch_name);
$smarty->assign('larch_name_subtitle', $larch_name_subtitle);

// Our database connection. User validation only needs read-only access.
$db_conn = mysql_connect_localhost_readonly($larch_db_name);

// The top level.
if ($_POST) {
	// Verify the username and password.
	$usrid = check_user($_POST, $db_conn);
	if (is_string($usrid)) {
		$smarty->assign("error", $usrid);
	} else {
		$_SESSION['usr_id'] = $usrid;
		$_SESSION['usr_username'] = $_POST['username'];
		// FIXME: Do we really need to keep this once logged in?
		$_SESSION['usr_pass'] = $_POST['password'];
		header("Location: tasks.php");
	}
} elseif ($_GET) {
	if ($_SESSION['usr_id']) {
		// User is already logged in, so go somewhere useful.
		header("Location: tasks.php");
	}
}

mysql_close();

$smarty->display('login.tpl');
?>
